# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
脚本类，用来对组合好的参数进行循环执行，依次带入组合参数请求。可加入对响应结果断言） 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import pymysql
import requests

from baseset.mssaasApi import API_SAAS
from logger import Logger

logger = Logger("mssaas").get_log()


c_url = 'https://test.ms-saas.msxiaodai.com/biz/'        # 企业端
u_url = 'https://test.ms-saas.msxiaodai.com/manage/'     # 业务端

db = pymysql.connect(
        host="10.16.20.182",
        # host="10.16.20.190",     # 开发环境
        user="dev",  # 测试：dev   开发：root
        password="dev",  # 测试：dev   开发：123456
        port=3306,
        use_unicode=True,
        charset="utf8",
        database="mssaasdb")
cursor = db.cursor()

c_headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
            'content-Type': 'application/json',
            "Cookie": "currenthostid=9;currentt=90b241e928528907c0cf03e3ef173b3eeb7317ba;"
        }

# admint=6bb3abc5e1bc8878293117ec81a7402380efa0a9; adminhostid=1
# admint=61f6a775d1110cc74b67b0505cd100615bcf64a2; adminhostid=2
u_headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
            'content-Type': 'application/json',
            "Cookie": "admint=61f6a775d1110cc74b67b0505cd100615bcf64a2; adminhostid=2"
        }

user_cookie ={
    "1": "admint=6bb3abc5e1bc8878293117ec81a7402380efa0a9; adminhostid=1",
    "2": "admint=61f6a775d1110cc74b67b0505cd100615bcf64a2; adminhostid=2",
    "3": "admint=64b9d0c56cfb5649da4d98c82a20c40e8440e528; adminhostid=3",
    "4": "admint=5d8ab52c8ce283c49ca5265563f901a21b9af3d5; adminhostid=4",
    "5": "admint=33a964ec10555740d8ca39a1a4222f76bf942bfe; adminhostid=5"
}

def get_user(m,n):
    username = []
    for i in range(m,n):
        no = '13111111' + str(i)
        username.append(no)
    return username


def get_enterpriseDate(username,status):
    sql = "select enterprise_no from enterprise_user where username=%s and account_status=%s;" % (username,status)
    cursor.execute(sql)
    results = cursor.fetchone()  # 一条数据
    if isinstance(results,tuple):
        enterpriseNo = results[0]
        return (enterpriseNo)


# ms_loan表查询还款中和逾期订单
def get_loanDate(status):
    sql = "select process_no from ms_loan where account_status=%s;" % (status)
    cursor.execute(sql)
    results = cursor.fetchone()  # 一条数据
    if isinstance(results, tuple):
        process_no = results[0]
        return (process_no)

# 1. 注册流程
def register(username):
    logger.info('企业用户注册开始---------')
    fc_url = c_url + 'user/register'
    data = API_SAAS['register']
    data['username'] = username
    req1 = requests.post(fc_url, json=data, headers=c_headers)
    print('注册企业用户名为：' + username)
    logger.info("接口响应信息：%s", req1.text)


# 2. 企业开户流程
def openAccount(username):
    logger.info('企业账户创建开始---------')
    fc_url = c_url + 'user/openAccount'
    data = API_SAAS['openAccount']
    data['username'] = username
    data['enterpriseName'] = '供应链企业' + username
    req1 = requests.post(fc_url, json=data, headers=c_headers)
    print('开户企业用户名为：' + username)
    logger.info("接口响应信息：%s", req1.text)


# 4. 企业借款申请开始
def apply(username,enterpriseNo):
    logger.info('企业借款申请开始---------')
    fc_url = c_url + 'order/apply'
    data = API_SAAS['apply']
    data['username'] = username
    data['enterpriseNo'] = enterpriseNo
    data['enterpriseName'] = '供应链企业' + username
    data['legalName'] = '法人' + username
    req1 = requests.post(fc_url, json=data, headers=c_headers)
    print('用户名为：' + username,'企业号为：' + enterpriseNo)
    logger.info("接口响应信息：%s", req1.text)


def saveVoucher(processNo):
    logger.info('企业上传线下还款凭证开始---------')
    fc_url = c_url + 'saveVoucher'
    data = API_SAAS['saveVoucher']
    data['processNo'] = processNo
    req1 = requests.post(fc_url, json=data, headers=c_headers)
    print('借款案件号为：' + processNo)
    logger.info("接口响应信息：%s", req1.text)

# 业务端接口

# 1. 开户审核流程
def approveEnterprise(userId,enterpriseNo):
    logger.info('后台开户审核开始---------')
    fu_url = u_url + 'approveEnterprise'
    data = API_SAAS['approveEnterprise']
    data['enterpriseNo'] = enterpriseNo
    u_headers['Cookie'] = user_cookie[userId]
    req1 = requests.post(fu_url, json=data, headers=u_headers)
    print('被审批的企业号：' + enterpriseNo)
    logger.info("接口响应信息：%s", req1.text)


# 1. 获取我的待办
def task_fetch(userId):
    logger.info('我的待办案件查询开始---------')
    fu_url = u_url + '/task/fetch'
    data = API_SAAS['task_fetch']
    data['userId'] = userId
    u_headers['Cookie'] = user_cookie[userId]
    req1 = requests.post(fu_url, json=data, headers=u_headers)
    print('操作的用户id为：' + userId)
    logger.info("接口响应信息：%s", req1.text)
    data = eval(req1.text)['detail']['result']['pageList']
    for task in data:
        #print(type(task),task)
        processNo = task['processNo']
        processNum = task['processNum']
        taskId = task['taskId']
        print(userId,processNo,processNum,taskId)
        task_complete(userId, processNo, processNum, taskId)



def task_complete(userId,processNo,processNum,taskId):
    logger.info('审批提交申请开始---------')
    fu_url = u_url + '/task/complete'
    data = API_SAAS['task_complete']
    if userId == '5':
        data['loanTime'] = '2019-06-19 15:00:00'
    else:
        pass
    data['userId'] = userId
    data['processNo'] = processNo
    data['processNum'] = processNum
    data['taskId'] = taskId
    data['rtfState'] = "Pass"                # Pass-通过  Reject-拒绝  BackToFirst-退回初审 出纳时候直接写死pass
    u_headers['Cookie'] = user_cookie[userId]
    req1 = requests.post(fu_url, json=data, headers=u_headers)
    print('案件号为：' + processNum,'企业号为：' + processNum)
    logger.info("接口响应信息：%s", req1.text)


def particulars(userId,processNo):
    logger.info('用户端获取案件信息开始---------')
    fu_url = u_url + '/case/particulars'
    data = API_SAAS['particulars']
    data['processNo'] = processNo
    u_headers['Cookie'] = user_cookie[userId]
    req1 = requests.post(fu_url, json=data, headers=u_headers)
    print('案件号为：' + processNo)
    logger.info("接口响应信息：%s", req1.text)


def main():
    username = get_user(100,201)   # 算头不算尾
    for user in username:
        # register(user)                            # 1.注册用户
        # openAccount(user)                         # 2.开立账户
        enterpriseNo = get_enterpriseDate(user,1)          # 开户状态：0-未开户，1-开户中，2-开户成功，3-开户失败，4-账户失效
        if isinstance(enterpriseNo, str):
            # print(enterpriseNo)
            approveEnterprise('1',enterpriseNo)     # 3.开户审核
            #apply(no, enterpriseNo)                # 4.申请进件


if __name__ == '__main__':
    #main()
    #task_fetch('2')   # 初审岗角色
    #task_fetch('3')   # 终审岗角色
    #task_fetch('4')  # 财务岗角色
    task_fetch('5')  # 出纳岗角色
    #particulars('2',"SCD201906180001")